import { useState } from 'react';
import { useDispatch } from 'react-redux';
import { ProCard } from '@ant-design/pro-components';
import { useHandler, useMount } from '@cfe/hooks';
import {
  Button,
  DatePicker,
  Form,
  Input,
  InputNumber,
  message,
  Select,
} from 'antd';
import dayjs from 'dayjs';
import { camelizeKeys, decamelizeKeys } from 'humps';
import { history, useAccess, useSearchParams, useSelector } from 'umi';

import { PreFixSpan } from '@/components/base';
import PageContainer from '@/components/PageContainer';
import { requestWithoutCache } from '@/utils/request';

import { sendMessage } from '../constants';

import FilterItem from './components/FilterItem';
import reduxInfoToFilterData from './utils/reduxInfoToFilterData';
import remoteFilterToFilterData from './utils/remoteFilterToFilterData';
import { getSelectedTags } from './utils/storage';
import { PRODUCT_TYPES } from './constants';

const { Option } = Select;
const { Item: FormItem, useForm } = Form;

const LabelConfigV2 = () => {
  const access = useAccess();
  const [form] = useForm();
  const [showFreq, setShowFreq] = useState(false);
  const dispatch = useDispatch();
  const [searchParams] = useSearchParams();
  const crowd_id = searchParams.get('crowd_id');
  const [initialValue, setInitialValue] = useState();
  const [submitDisabled, setSubmitDisabled] = useState(false);
  const copyLabels = useSelector(
    (state) => state.label.crowdSelectedGroupTags[crowd_id],
  );

  const handleValueChange = useHandler(() => {
    const formData = form.getFieldsValue();
    if (formData?.repeat_create) {
      const repeatCreateValue = form.getFieldValue('repeat_create');
      if (repeatCreateValue) {
        setShowFreq(repeatCreateValue === 'repeat');
      }
    }
  });

  useMount(() => {
    if (crowd_id) {
      requestWithoutCache(`/api/dmp/crowd/list?id=${crowd_id}`).then((res) => {
        const {
          filter,
          limit,
          name,
          product_type,
          refresh_interval,
          time_begin,
          time_end,
        } = res.data[0];
        const repeat_create = refresh_interval === 0 ? 'once' : 'repeat';
        const time = [dayjs(time_begin), dayjs(time_end)];
        setInitialValue(
          camelizeKeys(
            remoteFilterToFilterData(
              filter,
              reduxInfoToFilterData(copyLabels ?? []),
            ),
          ),
        );
        setShowFreq(repeat_create === 'repeat');
        form.setFieldsValue({
          limit,
          name,
          product_type,
          repeat_create,
          time,
          refresh_interval,
        });
      });
    } else {
      // 此处制作filter的数据
      const data = getSelectedTags() ?? [];
      setInitialValue(reduxInfoToFilterData(data));
    }
  });

  const handleSubmit = useHandler((values) => {
    const {
      filter,
      name,
      product_type,
      refresh_interval,
      repeat_create,
      time,
      limit = 0,
    } = values;
    const body = {
      filter: decamelizeKeys(filter),
      name,
      product_type,
      refresh_interval: repeat_create === 'once' ? 0 : refresh_interval,
      ...(repeat_create === 'repeat' && {
        time_begin: time[0].format('YYYYMMDD'),
        time_end: time[1].format('YYYYMMDD'),
      }),
      crowd_type: 1,
      limit,
    };
    setSubmitDisabled(true);
    requestWithoutCache(`/api/dmp/crowd/create`, {
      body: JSON.stringify(body),
      method: 'POST',
    })
      .then((resp) => {
        sendMessage({
          crowdName: body.name,
          crowdId: resp.data.crowd_id,
        });
        if (resp.status === 0) {
          message.success('创建成功');
          // 创建成功之后
          dispatch({ type: 'label/deleteGroupTagAll' });
          history.push('/tools/user-explorer/crowd?tab=myCrowd');
        } else {
          setSubmitDisabled(false);
        }
      })
      .catch(() => {
        setSubmitDisabled(false);
      });
  });
  return (
    <PageContainer
      backUrl="/tools/user-explorer/user-query"
      accessible={access.canRead}
    >
      <ProCard
        extra={
          <Button
            type="primary"
            onClick={() => {
              history.push(
                `/tools/user-explorer/user-query${
                  crowd_id ? `?crowd_id=${crowd_id}` : ''
                }`,
              );
            }}
          >
            增加标签
          </Button>
        }
      >
        <Form
          form={form}
          onValuesChange={handleValueChange}
          onFinish={handleSubmit}
          labelCol={{ span: 3 }}
        >
          <FormItem name="filter">
            <FilterItem initialValue={initialValue} />
          </FormItem>
          <Form.Item name="name" label="人群名称" rules={[{ required: true }]}>
            <Input style={{ width: '600px' }} />
          </Form.Item>
          <Form.Item label={<PreFixSpan>内容类型</PreFixSpan>}>
            <Form.Item name="product_type">
              <Select style={{ width: '600px' }}>
                {Object.keys(PRODUCT_TYPES).map((key) => (
                  <Option key={key} value={PRODUCT_TYPES[key]}>
                    {key}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <p style={{ margin: '-16px 0  -10px' }}>
              如有 idfa、oaid 等相关 id
              的导出场景，在创建生成人群包之后，选择「导出人群包」操作，此时选择对应的文件类型即可。
            </p>
          </Form.Item>
          <Form.Item name="limit" label="人群缩减">
            <InputNumber placeholder="请填写数字" style={{ width: '600px' }} />
          </Form.Item>
          <Form.Item
            name="repeat_create"
            label="生成方式"
            rules={[{ required: true }]}
          >
            <Select style={{ width: '600px' }}>
              <Option value="repeat">定时更新</Option>
              <Option value="once">一次性任务</Option>
            </Select>
          </Form.Item>
          {showFreq && (
            <Form.Item name="refresh_interval" label="更新频率">
              <Select style={{ width: '600px' }}>
                <Option value={1}>按天</Option>
                <Option value={2}>按周</Option>
                <Option value={3}>按月</Option>
              </Select>
            </Form.Item>
          )}
          {showFreq && (
            <Form.Item
              name="time"
              label="更新时间范围"
              rules={[{ required: true }]}
            >
              <DatePicker.RangePicker />
            </Form.Item>
          )}
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              style={{ position: 'relative', left: '750px' }}
              disabled={submitDisabled}
            >
              创建人群
            </Button>
          </Form.Item>
        </Form>
      </ProCard>
    </PageContainer>
  );
};

export default LabelConfigV2;
